#
# peerscape.discovery.advertise
#
# Copyright 2007-2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Toni Ruottu <toni.ruottu@iki.fi>
#          Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import logging
from time import time, sleep
from threading import Thread, currentThread

from messkit.nson import encode
from peerscape.discovery import lookup

VERSION = '3.0'

advertisement_threads = []

expirations = {}

def advertise(keys, value, ttl, minttl=None, async=True):
    keys = [(key + '-' + VERSION) for key in keys]
    value = encode(value)
    if minttl is None:
        minttl = ttl / 2

    if async:
        _advertise_async(keys, value, ttl, minttl)
    else:
        _advertise_sync(keys, value, ttl, minttl)

def _advertise_async(*args):
    def run():
        thread = currentThread()
        advertisement_threads.append(thread)
        try:
            _advertise_sync(*args)
        finally:
            advertisement_threads.remove(thread)

    thread = Thread(target=run, name='openlookup-advertisement-thread')
    thread.setDaemon(True)
    thread.start()

def _advertise_sync(keys, value, ttl, minttl):
    for key in keys:
        expiration = expirations.get((key, value), 0)
        if expiration - time() < minttl:
            try:
                lookup.put(key, value, ttl=ttl)
                expirations[(key, value)] = time() + ttl
            except lookup.Error, e:
                logging.warn('Advertising: %s' % e)
                sleep(30)
